#include "header.h"
#include <string>
using std::string;
extern GtkWidget *entry_player;
static string cppstr;

void
string_normalize (char *line, string & cppstr)
{
  char *savept = NULL;
  char *str;

  if ((str = strtok_r (line, " ", &savept)) != NULL)
    {
      cppstr += str;
      while ((str = strtok_r (NULL, " ", &savept)) != NULL)
	{
	  cppstr += " ";
	  cppstr += str;
	}
    }
}


void
load_config ()
{
  string path = getenv ("HOME");
  path += "/.feidian_monitor/config";
  FILE *fp = fopen (path.c_str (), "r");
  if (fp == NULL)
    {
      gtk_entry_set_text (GTK_ENTRY (entry_player),
			  "mplayer -ontop -geometry 100%:100%");
      cppstr = "mplayer -ontop -geometry 100%:100%";
    }
  else
    {
      char *line = NULL;
      size_t len = 0;
      if (getline (&line, &len, fp) != -1)
	{
	  string_normalize (line, cppstr);
	  gtk_entry_set_text (GTK_ENTRY (entry_player), cppstr.c_str ());
	}
      if (line)
	free (line);
      fclose (fp);
    }
}

void
save_config ()
{
  const char *line = gtk_entry_get_text (GTK_ENTRY (entry_player));
  char *line2 = strdup (line);
  string cppstr2;
  string_normalize (line2, cppstr2);

  if (cppstr != cppstr2)
    {
      string path = getenv ("HOME");
      path += "/.feidian_monitor/";
      if (access (path.c_str (), F_OK))
	mkdir (path.c_str (), S_IRWXU);
      path += "config";
      FILE *fp = fopen (path.c_str (), "w");
      if (fp == NULL)
	{
	  perror ("path to file config is invalid");
	  free (line2);
	  return;
	}
      fwrite (cppstr2.c_str (), 1, cppstr2.size (), fp);
      fclose (fp);
    }
  free (line2);
}
